/**
 * 编辑用户信息页面
 * 允许用户修改头像、昵称、性别、生日等个人信息
 */
import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Image,
  TextInput,
  Platform,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Icon from 'react-native-vector-icons/Ionicons';
import { useNavigation } from '@react-navigation/native';
import { useUser } from '../context/UserContext';
import { ToastManager } from '../components/Toast';
import ActionSheet from '../components/ActionSheet';
import { launchImageLibrary } from 'react-native-image-picker';
import { userAPI } from '../api';
import { COLORS, SHADOWS } from '../styles/constants';

export default function EditProfileScreen() {
  const insets = useSafeAreaInsets();
  const navigation = useNavigation();
  const { user, updateUser } = useUser();

  // 表单状态
  const [avatar, setAvatar] = useState(
    user?.avatar ||
      'https://images.unsplash.com/photo-1544723795-3fb6469f5b39?w=200',
  );
  const [nickname, setNickname] = useState(user?.nickname || '');
  const [gender, setGender] = useState(user?.sex ? String(user.sex) : '0'); // 0=未知/1=男/2=女
  const [signature, setSignature] = useState(user?.remark || '');
  const [phone] = useState(user?.phone || user?.tel || '');
  const [address] = useState(user?.address || '');
  const [loading, setLoading] = useState(false);
  const [uploadedAvatarUrl, setUploadedAvatarUrl] = useState(''); // 上传后的头像URL
  const [genderPickerVisible, setGenderPickerVisible] = useState(false);

  // 性别选择
  const handleGenderSelect = () => {
    setGenderPickerVisible(true);
  };

  // 选择头像
  const handleSelectAvatar = async () => {
    const options = {
      mediaType: 'photo',
      quality: 0.8,
      maxWidth: 800,
      maxHeight: 800,
    };

    launchImageLibrary(options, async response => {
      if (response.didCancel) {
        return;
      }
      if (response.errorCode) {
        ToastManager.error('选择图片失败');
        return;
      }
      if (response.assets && response.assets[0]) {
        const asset = response.assets[0];
        // 显示本地预览
        setAvatar(asset.uri);

        try {
          ToastManager.info('正在上传头像...');

          // 构造文件对象
          const file = {
            uri: asset.uri,
            type: asset.type || 'image/jpeg',
            name: asset.fileName || 'avatar.jpg',
          };

          // 上传到服务器
          const uploadResponse = await userAPI.uploadFile(file, 'avatar');

          // 获取上传后的URL
          const avatarUrl =
            uploadResponse?.data?.data?.url || uploadResponse?.data?.url;

          if (avatarUrl) {
            setUploadedAvatarUrl(avatarUrl);
            ToastManager.success('头像上传成功，保存后生效');
          } else {
            throw new Error('上传失败');
          }
        } catch {
          ToastManager.error('头像上传失败，请重试');
          // 恢复原头像
          setAvatar(
            user?.avatar ||
              'https://images.unsplash.com/photo-1544723795-3fb6469f5b39?w=200',
          );
        }
      }
    });
  };

  // 保存用户信息
  const handleSave = async () => {
    // 验证昵称
    if (!nickname.trim()) {
      ToastManager.error('请输入昵称');
      return;
    }
    if (nickname.length < 2 || nickname.length > 50) {
      ToastManager.error('昵称长度应为2-50个字符');
      return;
    }

    try {
      setLoading(true);

      // 准备更新数据
      const updateData = {
        nickname: nickname.trim(),
        sex: parseInt(gender) || 0,
        tel: phone || '',
        address: address || '',
        remark: signature.trim(),
        avatar: uploadedAvatarUrl || avatar || '',
      };

      // 调用API更新用户信息
      const response = await userAPI.updateProfile(updateData);

      if (response?.data?.code === 200) {
        // 更新本地用户信息
        await updateUser({
          nickname: updateData.nickname,
          sex: updateData.sex,
          tel: updateData.tel,
          address: updateData.address,
          remark: updateData.remark,
          avatar: updateData.avatar,
        });

        ToastManager.success('保存成功');
        setTimeout(() => {
          navigation.goBack();
        }, 500);
      } else {
        throw new Error(response?.data?.msg || '保存失败');
      }
    } catch (error) {
      ToastManager.error(error.message || '保存失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const getGenderText = () => {
    if (gender === '1') return '男';
    if (gender === '2') return '女';
    if (gender === '0') return '保密';
    return '未设置';
  };

  return (
    <View style={styles.container}>
      {/* 头部导航 */}
      <View style={[styles.header, { paddingTop: insets.top }]}>
        <View style={styles.headerContent}>
          <TouchableOpacity
            style={styles.headerButton}
            onPress={() => navigation.goBack()}
          >
            <Icon name="chevron-back" size={24} color="#333" />
          </TouchableOpacity>
          <Text style={styles.headerTitle}>编辑资料</Text>
          <View style={styles.headerPlaceholder} />
        </View>
      </View>

      <ScrollView
        style={styles.content}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps="handled"
        contentContainerStyle={styles.scrollContent}
      >
        {/* 头像编辑 */}
        <TouchableOpacity
          style={styles.avatarSection}
          onPress={handleSelectAvatar}
          activeOpacity={0.8}
        >
          <Text style={styles.label}>头像</Text>
          <View style={styles.avatarContainer}>
            <Image source={{ uri: avatar }} style={styles.avatar} />
            <Icon name="chevron-forward" size={20} color="#c4c4c4" />
          </View>
        </TouchableOpacity>

        {/* 昵称编辑 */}
        <View style={styles.inputSection}>
          <Text style={styles.label}>昵称</Text>
          <TextInput
            style={styles.input}
            value={nickname}
            onChangeText={setNickname}
            placeholder="请输入昵称"
            placeholderTextColor="#c4c4c4"
            maxLength={20}
          />
        </View>

        {/* 性别选择 */}
        <TouchableOpacity
          style={styles.inputSection}
          onPress={handleGenderSelect}
          activeOpacity={0.8}
        >
          <Text style={styles.label}>性别</Text>
          <View style={styles.selectContainer}>
            <Text style={[styles.selectText, !gender && styles.placeholder]}>
              {getGenderText()}
            </Text>
            <Icon name="chevron-forward" size={20} color="#c4c4c4" />
          </View>
        </TouchableOpacity>

        {/* 个性签名 */}
        <View style={styles.textareaSection}>
          <Text style={styles.label}>个性签名</Text>
          <TextInput
            style={styles.textarea}
            value={signature}
            onChangeText={setSignature}
            placeholder="写下你的个性签名..."
            placeholderTextColor="#c4c4c4"
            multiline
            maxLength={100}
            textAlignVertical="top"
          />
          <Text style={styles.charCount}>{signature.length}/100</Text>
        </View>

        {/* 提示信息 */}
        <View style={styles.tipSection}>
          <Icon name="information-circle-outline" size={16} color="#999" />
          <Text style={styles.tipText}>修改后的信息将在所有设备上同步显示</Text>
        </View>

        {/* 保存按钮 */}
        <TouchableOpacity
          style={[styles.saveButton, loading && styles.saveButtonDisabled]}
          onPress={handleSave}
          disabled={loading}
          activeOpacity={0.8}
        >
          <Text style={styles.saveButtonText}>
            {loading ? '保存中...' : '保存'}
          </Text>
        </TouchableOpacity>
      </ScrollView>

      {/* 性别选择器 */}
      <ActionSheet
        visible={genderPickerVisible}
        title="选择性别"
        options={[
          {
            label: '男',
            onPress: () => {
              setGender('1');
              setGenderPickerVisible(false);
            },
          },
          {
            label: '女',
            onPress: () => {
              setGender('2');
              setGenderPickerVisible(false);
            },
          },
          {
            label: '保密',
            onPress: () => {
              setGender('0');
              setGenderPickerVisible(false);
            },
          },
        ]}
        onCancel={() => setGenderPickerVisible(false)}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background.secondary,
  },
  header: {
    backgroundColor: COLORS.background.card,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: COLORS.border.light,
  },
  headerContent: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    width: '100%',
    ...Platform.select({
      ios: { height: 44 },
      android: { height: 56 },
      default: { height: 44 },
    }),
  },
  headerButton: {
    padding: 4,
    minWidth: 60,
    height: 36,
    justifyContent: 'center',
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: COLORS.text.primary,
  },
  headerPlaceholder: {
    width: 60,
  },
  content: {
    flex: 1,
  },
  scrollContent: {
    paddingBottom: 32,
  },
  avatarSection: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: COLORS.background.card,
    paddingHorizontal: 16,
    paddingVertical: 16,
    marginTop: 12,
    borderTopWidth: StyleSheet.hairlineWidth,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderColor: COLORS.border.light,
  },
  avatarContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  avatar: {
    width: 60,
    height: 60,
    borderRadius: 30,
    marginRight: 8,
  },
  label: {
    fontSize: 16,
    color: COLORS.text.primary,
    fontWeight: '500',
  },
  inputSection: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: COLORS.background.card,
    paddingHorizontal: 16,
    paddingVertical: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderColor: COLORS.border.light,
  },
  input: {
    flex: 1,
    fontSize: 16,
    color: COLORS.text.primary,
    textAlign: 'right',
    marginLeft: 16,
    padding: 0,
  },
  selectContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  selectText: {
    fontSize: 16,
    color: COLORS.text.primary,
    marginRight: 8,
  },
  placeholder: {
    color: COLORS.text.placeholder,
  },
  textareaSection: {
    backgroundColor: COLORS.background.card,
    paddingHorizontal: 16,
    paddingVertical: 16,
    marginTop: 12,
    borderTopWidth: StyleSheet.hairlineWidth,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderColor: COLORS.border.light,
  },
  textarea: {
    fontSize: 16,
    color: COLORS.text.primary,
    minHeight: 80,
    marginTop: 8,
    padding: 0,
  },
  charCount: {
    fontSize: 12,
    color: COLORS.text.quaternary,
    textAlign: 'right',
    marginTop: 8,
  },
  tipSection: {
    flexDirection: 'row',
    alignItems: 'center',
    marginHorizontal: 16,
    marginTop: 16,
    padding: 12,
    backgroundColor: COLORS.primaryLight,
    borderRadius: 8,
    borderWidth: StyleSheet.hairlineWidth,
    borderColor: COLORS.primarySoft,
  },
  tipText: {
    flex: 1,
    fontSize: 13,
    color: COLORS.text.tertiary,
    marginLeft: 8,
  },
  saveButton: {
    marginHorizontal: 16,
    marginTop: 24,
    paddingVertical: 16,
    borderRadius: 30,
    backgroundColor: COLORS.primary,
    alignItems: 'center',
    justifyContent: 'center',
    ...SHADOWS.md,
  },
  saveButtonDisabled: {
    backgroundColor: COLORS.border.dark,
    shadowOpacity: 0.1,
  },
  saveButtonText: {
    fontSize: 16,
    fontWeight: '600',
    color: COLORS.white,
  },
});
